import axios from "axios";
import store from "@/store";
import router from "@/router";
import { removeToken, setToken } from "@/utils/auth";

let baseURL =
  process.env.NODE_ENV == "development"
    ? "https://membe.e-kc.vip/"
    : "https://membe.e-kc.vip/";

let baseURL1 =
  process.env.NODE_ENV == "development"
    ? "https://api.e-kc.vip/"
    : "https://api.e-kc.vip/";
const instance = axios.create({
  baseURL: baseURL,
  timeout: 8000,
});

//普通数据列表
const request = axios.create({
  baseURL: baseURL1,
  timeout: 8000,
});

// 添加请求拦截器
instance.interceptors.request.use(
  function (config) {
    // 判断 token 是否存在，如果存在直接添加到请求头中
    const isToken = JSON.parse(sessionStorage.getItem("membe_token"));
    if (isToken) {
      config.headers.Authorization = `${isToken.Access_Token}`;
    }
    return config;
  },
  function (error) {
    console.log(error.response);
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
instance.interceptors.response.use(
  function (response) {
    return response;
  },
  async function (error) {
    if (error.response.status === 401) {
      let obj = JSON.parse(window.sessionStorage.getItem("membe_token"));
      let res = await axios({
        url: `${baseURL}/Login/refresLogin`,
        method: "post",
        headers: {
          Authorization: obj.Refresh_Token,
        },
      });
      if (res.data.status === 200) {
        obj.Refresh_Token = res.data.data.Refresh_Token;
        obj.Access_Token = res.data.data.Access_Token;
        setToken(obj);
      } else {
        store.commit("tags/clearTags");
        store.commit("user/removeUserInfo");
        store.commit("user/removeMenu");
        removeToken();
        router.push("/login");
      }
    }
  }
);

export { instance, request, baseURL1 };
